package com.agentai.framework.manager;

import com.agentai.framework.thread.ThreadPool;
import com.agentai.framework.thread.Threads;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * 异步任务管理器
 *
 * @author fuzhilin
 */
public class AsyncManager {

    private static final Logger log = LoggerFactory.getLogger(AsyncManager.class);
    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 1;

    public static final int CORE_POPL_SIZE = 4;
    /**
     * 异步操作任务调度线程池
     */
    private final ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(CORE_POPL_SIZE,
            new BasicThreadFactory.
                    Builder().namingPattern("common-schedule-pool-%d").daemon(true).build());

    private ScheduledExecutorService scheduledExecutorService = null;

    private ExecutorService executorService = ThreadPool.newCachedThreadPool();

    /**
     * 单例模式
     */
    private AsyncManager() {
    }

    private static final AsyncManager me = new AsyncManager();

    public static AsyncManager me() {
        return me;
    }

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void executeCache(TimerTask task) {
        try {
            ThreadPool.newFixedThreadPool().execute(task);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 使用固定的线程池执行定时任务，以减少线程创建的开销
     *
     * @param task 要执行的定时任务
     */
    public void executeCache2(TimerTask task) {
        try {
            ThreadPool.newFixedThreadPool2().execute(task);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 停止任务线程池
     */
    public void shutdown() {
        log.info("关闭线程池--------");
        Threads.shutdownAndAwaitTermination(executor);
    }
}
